package com.zhouqinuan.spring.cloud.develop.framework.fastdfs.config;

import java.net.InetSocketAddress;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zhouqinuan.spring.cloud.develop.framework.fastdfs.FastDFSProperties;
import com.zhouqinuan.spring.cloud.develop.framework.fastdfs.service.FastDFSService;

import lombok.extern.slf4j.Slf4j;

@Configuration
@EnableConfigurationProperties({ FastDFSProperties.class })
@Slf4j
public class FastDFSAutoConfiguration {

    @Autowired
    private FastDFSProperties fastDFSProperties;

    @Bean
    public TrackerClient trackerClient() throws Exception {

        log.info("Begin to initialize FastDFS...");

        ClientGlobal.setG_connect_timeout(fastDFSProperties.getConnectTimeoutInSeconds() * 1000);
        ClientGlobal.setG_network_timeout(fastDFSProperties.getNetworkTimeoutInSeconds() * 1000);
        ClientGlobal.setG_charset(fastDFSProperties.getCharset());
        ClientGlobal.setG_tracker_http_port(fastDFSProperties.getHttpTrackerHttpPort());
        ClientGlobal.setG_anti_steal_token(fastDFSProperties.isHttpAntiStealToken());
        ClientGlobal.setG_secret_key(fastDFSProperties.getHttpSecretKey());
        String[] szTrackerServers = fastDFSProperties.getTrackerServers().split(",");

        if (szTrackerServers == null) {
            throw new MyException("item \"tracker_server\" not found");

        } else {
            InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
            for (int i = 0; i < szTrackerServers.length; ++i) {
                String[] parts = szTrackerServers[i].split("\\:", 2);
                if (parts.length != 2) {
                    throw new MyException(
                            "the value of item \"tracker_server\" is invalid, the correct format is host:port");
                }

                tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
            }
            TrackerGroup trackerGroup = new TrackerGroup(tracker_servers);
            ClientGlobal.setG_tracker_group(trackerGroup);
        }

        TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);

        log.info("End to initialize FastDFS...");

        return trackerClient;
    }

    @Bean
    public FastDFSService fastDFSService(TrackerClient trackerClient) throws Exception {
        FastDFSService fastDFSService = new FastDFSService();
        fastDFSService.setTrackerClient(trackerClient);
        fastDFSService.setUploadHost(fastDFSProperties.getUploadHost());

        return fastDFSService;
    }
}
